/**
 * 修改日期20190606：安全加强版用户管理
 * 参数e._op='get'/'save'/'delete'/'list',get是缺省参数
 * _op==get:需要提供_id,否则openid自己
 * _op==save:需要提供_id,否则openid自己
 * _op==list:需要提供_skip=0，_where={},每页100条记录
 * _op==delete:需要提供_id
 */
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command
const table = 'user'
const timenow = (new Date()).valueOf() + 28800000
let ops = ['get', 'save', 'list', 'delete', 'count']
exports.main = async (e, context) => {
  delete(e.userInfo)
  const {
    OPENID
  } = cloud.getWXContext()
  if (typeof OPENID == 'undefined' || !OPENID) {
    console.error('OPENID undefined')
    return false;
  }
  let myself, resData, op, srow, rrow;
  let query = await db.collection(table).where({
    openid: OPENID
  }).limit(1).get()
  if (!query.data.length) {
    try {
      srow = await db.collection(table).add({
        data: {
          openid: OPENID,
          users: {},
          rank: 0,
          createtime: timenow,
          modifytime: timenow,
        }
      })
      rrow = await db.collection(table).doc(srow._id).get()
      myself = rrow.data || {};
    } catch (err) {
      console.error(err)
    }
  } else {
    myself = query.data[0]
  }
  // delete myself.openid;
  if (typeof e._op == 'undefined') op = 'get';
  else if (typeof e._op == 'string') op = e._op;
  delete e._op;
  if (ops.indexOf(op) == -1) {
    console.error('missing-op')
    return false;
  }
  switch (op) {
    case 'get': {
      if (typeof e._id == 'string' && e._id != '') {
        let userRow = await db.collection(table).doc(e._id).get()
        resData = userRow.data || {};
      } else {
        resData = myself
      }
      break;
    }
    case 'save': {
      let saveData = e;
      saveData.modifytime = timenow
      let saveId = myself._id
      if (typeof e._id == 'string' && e._id != '' && e._id != saveId) {
        if (myself.rank < 5) {
          console.error('rank-too-low')
          return false;
        }
        saveId = e._id
        delete saveData._id
      }
      if (typeof e.rank != 'undefined') { //堵死改权限
        saveData.rank = 0;
      }
      srow = await db.collection(table).doc(saveId).update({
        data: saveData
      })
      rrow = await db.collection(table).doc(saveId).get()
      resData = rrow.data || {};
      delete resData.openid
      break;
    }
    case 'delete': {
      if (typeof e._id != 'string' || e._id == myself._id || myself.rank < 5) {
        console.error('delete-error')
        return false;
      }
      resData = await db.collection(table).doc(e._id).remove()
      break;
    }
    case 'list': { //
      let skip = (typeof e._skip == 'number' && e._skip > 0) ? e._skip : 0
      let where = (typeof e._where == 'object') ? e._where : {}
      where['authorized'] = 1
      rrow = await db.collection(table)
        .where(where)
        .orderBy('rank', 'desc')
        .orderBy('modifytime', 'desc')
        .orderBy('createtime', 'desc')
        .skip(skip)
        .limit(100)
        .get()
      resData = rrow.data
      resData = resData.map(function (k) {
        delete k.openid;
        return k;
      })
    }
    break;
  case 'count': {
    rrow = await db.collection(table).where({
      authorized: 1
    }).count()
    resData = rrow.total
  }
  break;
  }
  return resData;
}